import { Button, Card } from "antd";
import * as echarts from "echarts";
import { useEffect, useRef, useState } from "react";

const Bar: React.FC = () => {
  // 表格所在的div的ref
  const contariner = useRef<any>(null);
  // 表格配置项options
  const [options] = useState({
    title: {
      text: "销量示例",
    },
    legend: {
      data: ["销量", "库存"],
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: "none",
        },
        restore: {},
        saveAsImage: {},
      },
    },
    xAxis: {
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
    },
    yAxis: {},
    series: [
      {
        name: "销量",
        type: "bar",
        data: [5, 20, 36, 10, 10, 20],
      },
      {
        name: "库存",
        type: "bar",
        data: [15, 10, 26, 20, 20, 10],
      },
    ],
  });

  // 点击修改表格项options内容
  const update = () => {
    // 更新表格内容 先注销掉已有的表格 再重新初始化
    echarts.init(contariner.current).dispose();
    initCharts();
  };

  // 初始化表格的函数
  const initCharts = () => {
    const chart: any = echarts.init(contariner.current);
    chart.setOption(options);
  };

  // 页面加载时候初始化表格
  useEffect(() => {
    initCharts();
    // 表格初始化了
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <Card>
        <Button type="primary" onClick={update}>
          更新内容
        </Button>
      </Card>

      <Card title="柱状图">
        <div
          ref={contariner}
          style={{ width: "1550px", height: "580px" }}
        ></div>
      </Card>
    </div>
  );
};

export default Bar;
